<template>
  <div>
    <el-form class="query-form" @submit.native.prevent :inline="true">
      <el-form-item>
        <select-address
          v-model="params['customer_address_code.codelike']"
          auto-top
          clearable
          placeholder="所属地"
          @change="getData()"
        ></select-address>
      </el-form-item>

      <el-form-item>
        <el-input
          v-model="params.business_name"
          :clearable="true"
          placeholder="经营者查询"
          @change="getData()"
        ></el-input>
      </el-form-item>

      <el-form-item>
        <el-input
          v-model="params.submit_person_name"
          :clearable="true"
          placeholder="操作用户"
          @change="getData()"
        ></el-input>
      </el-form-item>

      <el-form-item>
        <el-button @click="getData()">查询</el-button>
      </el-form-item>

      <el-form-item class="float-right">
        <el-button type="primary" icon="el-icon-upload2" @click="handleUpload()">导入</el-button>
        <el-button
          type="primary"
          icon="el-icon-download"
          :loading="exportLoading"
          @click="handleDownload()"
        >
          导出
        </el-button>
      </el-form-item>
    </el-form>

    <c-table
      border
      class="table-sm"
      v-loading="loading"
      :stripe="false"
      :columns="tableColumns"
      :data="tableData"
    ></c-table>

    <div class="query-pagination">
      <div></div>
      <el-pagination
        layout="total, prev, pager, next, jumper"
        :current-page.sync="params.index"
        :page-size="params.size"
        :total="tableCount"
        @current-change="getData"
      ></el-pagination>
    </div>

    <import-excel
      :visible.sync="importDialogVisible"
      :title="`导入${dataName}`"
      :post-api="importUrl"
      :excel-template="`/static/files/${dataName}导入模板.xlsx`"
      @success="getData(params.index)"
    ></import-excel>

    <el-dialog
      top="30px"
      width="800px"
      :title="`${attachViewMode ? '查看' : '上传'}附件`"
      :close-on-click-modal="false"
      :visible.sync="attachVisible"
    >
      <upload-oss
        multiple
        accept="image/*"
        listType="picture-card"
        ref="upload_oss"
        auto-upload
        v-if="!attachViewMode"
        :file-list="attachImages"
        :on-remove="handleAttachRemove"
        :on-complete="handleAttachImagesComplete"
      ></upload-oss>
      <ul class="list-inline" v-else>
        <li class="attach-item" v-for="(img, index) in attachImages" :key="index">
          <img :src="img.url" class="attach-item-img" alt="" @click="handleAttachPreview(index)" />
        </li>
      </ul>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import SelectAddress from '@/components/select/SelectAddress'
import ImportExcel from '@/components/ImportExcel'
import { arrayFromString } from '@vimi/utils-tool'

export default {
  components: {
    SelectAddress,
    ImportExcel,
  },
  props: {},
  data() {
    return {
      loading: false,
      tableName: 'datum_customer_ele_table_import',
      dataName: '用电信息',
      params: {
        index: 1,
        size: 20,
        customer_name: '',
        submit_person_name: '',
        'customer_address_code.codelike': '',
        'submit_type.eq': '',
      },

      tableData: [],
      tableCount: 0,
      tableColumns: [
        { attrs: { label: '经营者姓名', prop: 'business_name' } },
        { attrs: { label: '身份证号码', prop: 'lender_idcard' } },
        { attrs: { label: '电表号', prop: 'ele_table_no' } },
        { attrs: { label: '开户地址', prop: 'ele_table_address' } },
        { attrs: { label: '开户户名', prop: 'ele_table_account' } },
        { attrs: { label: '附件', prop: 'attachCount', align: 'center' } },
        {
          attrs: { label: '操作', align: 'center', minWidth: '100px' },
          operations: [
            {
              name: '查看',
              icon: 'el-icon-search',
              event: this.handleAttachView,
              ifRender: row => row.attachCount,
            },
            {
              name: '上传',
              icon: 'el-icon-plus',
              attrs: { class: 'text-danger py-0 px-2' },
              event: this.handleAttachUpload,
            },
          ],
        },
      ],

      // 导入、导出
      importDialogVisible: false,
      importUrl: '',
      exportLoading: false,

      // 附件
      attachVisible: false,
      attachImages: [],
      attachViewMode: false,
      attachSaveLoading: false,
      attachId: '',
    }
  },
  computed: {
    ...mapGetters(['org']),
    attachPreviewImages() {
      return this.attachImages.map(img => {
        return { src: img.url, title: img.name }
      })
    },
  },
  watch: {},
  created() {
    this.params['customer_address_code.codelike'] = this.$utils.getAddressCode()
    this.importUrl = `/api/credit/import/?importKey=${this.tableName}_template`
    this.params['submit_type.eq'] = this.$utils.getClientOrgClass() === 'org_gov_ny' ? '1' : '4'
    this.getData()
  },
  mounted() {},
  methods: {
    async getData(index = 1) {
      this.params.index = index
      this.loading = true
      const [res] = await this.$utils.promise(
        this.$api.getData(this.$serviceName, `${this.tableName}_view`, this.params)
      )
      this.loading = false
      const data = (res && res.data) || {}
      this.tableData = (data.data || []).map(item => {
        item.attachImages = arrayFromString(item.attachment).map(url => {
          return { name: '附件', url }
        })
        item.attachCount = item.attachImages.length || ''
        return item
      })
      this.tableCount = data.totalCount || 0
    },
    handleUpload() {
      this.importDialogVisible = true
    },
    async handleDownload() {
      const { index, size, ...params } = this.params // eslint-disable-line
      const exportParams = {
        service: this.$serviceName,
        table: `${this.tableName}_view`,
        params: params,
        filename: `${this.dataName}.xlsx`,
      }
      this.exportLoading = true
      await this.$utils.promise(this.$api.exportData(exportParams))
      this.exportLoading = false
    },

    // 附件
    handleAttachView(row) {
      this.attachId = row.credit_ele_table_id
      this.attachImages = row.attachImages
      this.attachViewMode = true
      this.attachVisible = true
    },
    handleAttachUpload(row) {
      this.attachId = row.credit_ele_table_id
      this.attachImages = row.attachImages
      this.attachViewMode = false
      this.attachVisible = true
    },
    handleAttachPreview(index) {
      this.$utils.viewer({
        images: this.attachPreviewImages,
        index,
      })
    },
    handleAttachImagesComplete(images = []) {
      this.updateAttach(this.getImagesString(images))
    },
    handleAttachRemove(img) {
      const images = [...this.attachImages]
      const index = images.findIndex(it => it.url === img.url)
      if (index > -1) {
        images.splice(index, 1)
        this.updateAttach(this.getImagesString(images))
      }
    },
    async updateAttach(imagesStr = '') {
      this.attachSaveLoading = true
      const [res] = await this.$utils.promise(
        this.$api.updateData('credit', this.tableName, this.attachId, {
          attachment: imagesStr,
        })
      )
      this.attachSaveLoading = false
      if (res) {
        this.$message.success('操作成功！')
        this.getData()
      } else {
        this.$message.error('操作失败，请重试！')
      }
    },
    getImagesString(images = []) {
      return images.length ? `["${images.map(img => img.url).join('","')}"]` : ''
    },
  },
}
</script>

<style lang="scss" scoped>
.attach-item {
  display: inline-block;
  vertical-align: top;
  margin-right: 5px;
  margin-bottom: 5px;
}

.attach-item-img {
  width: 148px;
  height: 148px;
  border-radius: 4px;
  border: 1px solid #c0ccda;
  padding: 2px;
  cursor: pointer;
}
</style>
